#version 120 


uniform sampler2D positions;
uniform sampler2D velocities;
uniform sampler2D infos;
uniform sampler2D targets;
uniform vec3 randomSeed;
uniform bool active;
uniform float time;

float rand (vec2 n){
  return fract(sin(dot(n.xy, randomSeed.xy))* randomSeed.z);
}

void main(){
	
	vec3 newVelocity  = texture2D (velocities, gl_TexCoord[0].xy).xyz;
	vec3 newPosition = texture2D (positions, gl_TexCoord[0].xy).xyz;
	vec3 newInfos     = texture2D (infos, gl_TexCoord[0].xy).xyz;
	vec3 targetPos    = texture2D (targets, gl_TexCoord[0].xy).xyz;
	
	if (active && targetPos.x!=0) {
		newVelocity = targetPos - newPosition;
		if(length(targetPos-newPosition)<5) {
			newVelocity += 10*vec3(rand(gl_TexCoord[0].xy+vec2(1000,0))*2-1,rand(gl_TexCoord[0].xy+vec2(2000,0))*2-1,rand(gl_TexCoord[0].xy+vec2(1000,0))-0.5);
		}
	}
	
	// add gravity
	newVelocity += vec3(rand(gl_TexCoord[0].xy+vec2(1000,0))*2-1,rand(gl_TexCoord[0].xy+vec2(2000,0))*2-1,rand(gl_TexCoord[0].xy+vec2(1000,0))*0.2-0.1);
	//newVelocity += vec3(2,0,0);
	
	gl_FragData[0] = vec4(newPosition, 0);
	gl_FragData[1] = vec4(newVelocity, 1);
	gl_FragData[2] = vec4(newInfos, 1);
}